<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  news
 */

class m_news_actions_block_FormAction extends m_backoffice_extends_FormModal
{
	public function execute()
	{
        $errors = array();

        $this->addToModel('formValues', array('picture' => null));

        if($this->getRequestParameter('type') == 'add')
        {
            $newsItem = m_news_documents_Item::createNew()->setLang($this->getRequestParameter("docLang"));
            $folder = f_document_Provider::getInstance()->getByModelAndUniqueId('backoffice/Folder', $this->getRequestParameter("docId"), $this->getRequestParameter("docLang"));
        }
        else
        {
            $newsItem = f_document_Provider::getInstance()->getByModelAndUniqueId('news/Item', $this->getRequestParameter("docId"), $this->getRequestParameter("docLang"));
            $folder = $newsItem->getDocumentParent();
        }
		
		$formProvider = f_form_Provider::getInstance();
		
		$formProvider->setDocumentName("news")
		             ->setModuleName("news")
		             ->setFormName("FormNews");

		$values = $formProvider->getParams();

		if($formProvider->isSubmitted())
		{
			if($formProvider->isValid())
			{
                $dates = m_news_services_ItemService::getInstance()->formatDateForInsert($values['formValues']['publicationStart'], $values['formValues']['publicationEnd']);

                if(empty($values['formValues']['url']))
                {
                    $values['formValues']['url'] = f_core_Routing::formatStringForUrl($values['formValues']['label'], true);
                }

                $website = $this->getContextWebsite();

                $newsItem
						->setAuthor($this->getUser()->getlogin())
						->setPublicationstatus($values['formValues']['status'])
						->setLabel($values['formValues']['label'])
						->setEventDates($values['formValues']['eventDates'])
						->setStartpublicationdate($dates["dateStart"])
						->setEndpublicationdate($dates["dateEnd"])
						->setHeader($values['formValues']['intro'])
						->setContent($values['formValues']['content'])
						->setPictures($values['formValues']['picture'])
                        ->setUrl($values['formValues']['url'])
                        ->setWebsiteId($website->getUniqueId());

                if($values['formValues']['preview'] == 'true')
                {
                    m_backoffice_services_TempDocService::getInstance()->saveTemporaryDocument($newsItem);
                    $errors['status'] = "preview";
                    $this->fireLog($newsItem->getPreviewUrl());
                    $this->addToModel('previewUrl', $newsItem->getPreviewUrl());
                    $this->addToModel('formValues', $values['formValues']);
                }
                else
                {
                    m_backoffice_services_TempDocService::getInstance()->deleteTempDocument($newsItem->getUniqueId(), $newsItem->getLang());
                    
					$newsItem->save(false);

                    if($this->getRequestParameter('type') == 'add')
                    {
                        $folder->addItem($newsItem, 0)->save(false);
                    }

                    $this->closeModalAndRefresh();
                }
			}
			else
			{
				$errors = $formProvider->getErrors();
                $this->addToModel('formValues', $values['formValues']);
			}
		}
        else
        {
            if($this->getRequestParameter('type') == 'edit')
            {
                $this->addToModel('formValues', $this->getFormValuesFromDoc($newsItem));
            }
        }

        $pages = m_website_services_PageService::getInstance()->searchPagesByBlockParameters(array('action'=>'front_News'), $this->getRequestParameter("docLang"), $this->getContextWebsite()->getUniqueId());

        $this->setModalParameters();
		$this->addToModel("canPreview", count($pages) > 0);
		$this->addToModel("errors", $errors);
		$this->setView('success');
	}

    public function validate()
    {
        return $this->getUserContext()->hasRight(array("news_Add", "news_Edit"), 'OR');
    }

    private function getFormValuesFromDoc($newsItem)
    {
        $result['status'] = $newsItem->getPublicationstatus();
        $result['url'] = $newsItem->getUrl();
        $result['label'] = $newsItem->getLabel();
        $result['eventDates'] = $newsItem->getEventDates();
        $result['publicationStart'] = $newsItem->getStartpublicationdate();
        $result['publicationEnd'] = $newsItem->getEndpublicationdate();
        $result['intro'] = $newsItem->getHeader();
        $result['content'] = $newsItem->getContent();
        $result['picture'] = $newsItem->getPictures();

        return $result;
    }
}